#!/usr/bin/env python
# -*- coding: utf_8 -*-
"""
 Modbus TestKit: Implementation of Modbus protocol in python

 (C)2009 - Luc Jean - luc.jean@gmail.com
 (C)2009 - Apidev - http://www.apidev.fr

 This is distributed under GNU LGPL license, see license.txt
"""

from __future__ import print_function
from time import sleep

import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_tcp, hooks
import logging

from numpy import arange
from core import LOGGER

##from Ctgust_BMS.core import LOGGER
dataLogger = LOGGER#getDataLogger('datalogger','monitordata-200ms.log',200)
def main():
    """main"""
    logger = modbus_tk.utils.create_logger("console", level=logging.DEBUG)

    def on_after_recv(data):
        master, bytes_data = data
        #logger.info(bytes_data)

    hooks.install_hook('modbus.Master.after_recv', on_after_recv)

    try:

        def on_before_connect(args):
            master = args[0]
            logger.debug("on_before_connect {0} {1}".format(master._host, master._port))

        hooks.install_hook("modbus_tcp.TcpMaster.before_connect", on_before_connect)

        def on_after_recv(args):
            response = args[1]
            #logger.debug("on_after_recv {0} bytes received".format(len(response)))

        hooks.install_hook("modbus_tcp.TcpMaster.after_recv", on_after_recv)

        # Connect to the slave
        master = modbus_tcp.TcpMaster(host="192.168.43.131",port=1252)
        master.set_timeout(5.0)
        logger.info("connected")

        #logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 3))
        # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2, data_format='f'))
        # Read and write floats
        # master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, starting_address=0, output_value=[3.14], data_format='>f')
        # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2, data_format='>f'))
        # send some queries
        '''
        logger.info(master.execute(1, cst.READ_COILS, 0, 10))
        logger.info(master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 8))
        logger.info(master.execute(1, cst.READ_INPUT_REGISTERS, 100, 3))
        logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 100, 12))
        logger.info(master.execute(1, cst.WRITE_SINGLE_COIL, 7, output_value=1))
        logger.info(master.execute(1, cst.WRITE_SINGLE_REGISTER, 100, output_value=54))
        logger.info(master.execute(1, cst.WRITE_MULTIPLE_COILS, 0, output_value=[1, 1, 0, 1, 1, 0, 1, 1]))
        logger.info(master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 100, output_value=xrange(12)))
        '''
        data = [7.756, -0.5, -5.0, 0.04, 73.2]#1.2,-2.3,3.4,-4.5,5.6]
        #print(master.execute(1,cst.WRITE_MULTIPLE_REGISTERS,100,output_value=data,data_format=">fffff"))
        print(master.execute(1,cst.READ_HOLDING_REGISTERS,100,10))
        print("BatteryState:{}".format(master.execute(1,cst.READ_HOLDING_REGISTERS,100,10,data_format='>fffff')))
        print("ChargeState:{}".format(master.execute(1,cst.READ_HOLDING_REGISTERS,200,8,data_format='>ffff')))
        print("DisChargeState:{}".format(master.execute(1,cst.READ_HOLDING_REGISTERS,300,8,data_format='>ffff')))
        sleep(1)
    except modbus_tk.modbus.ModbusError as exc:
        logger.error("%s- Code=%d", exc, exc.get_exception_code())
    dataAry = [1,2,3,4,5,6,7,8,9,10]*1200
    while True:
        address = int(input("请输入遥控地址(20:充电,21:放电):"))
        val1 = int(input("输入开关量(0,1):"))
        dataLogger.info("发送遥控指令：{}".format(master.execute(1,cst.WRITE_SINGLE_COIL,address,1,output_value=val1)))
        dataLogger.info("开始发送遥调指令(6000)")
        for i in range(1,50):
            print('.',end='')#{}.{}'.format(i,dataAry[i*120:i*120+120]))
            master.execute(1,cst.WRITE_MULTIPLE_REGISTERS,address,i*120,output_value=dataAry[i*120:i*120+120])
        dataLogger.info("遥调指令发送完毕")#：{}".format(master.execute(1,cst.WRITE_MULTIPLE_REGISTERS,address,1,output_value=dataAry)))
        dataLogger.info("开始读取遥测指令(6000)")
        for i in range(1,50):
            resultData = master.execute(1,cst.READ_HOLDING_REGISTERS,i*120,120)
            #dataLogger.info("读取数据：{}".format(resultData))
            print('.',end='')
        dataLogger.info("遥测数据读取完毕")
if __name__ == "__main__":
    main()
    
